package com.spring.boot.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @version 1.0.0
 * @Date: 2022/11/3 11:04
 * @Author ZhuYouBin
 * @Description
 */
@RestController
@RequestMapping("/api/redis")
public class RedisController {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping("/set")
    public String set() {
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        for (int i = 0; i < 6; i++) {
            ops.set("k" + i, "v" + i + "00");
        }
        ops.set("k22", "v2200", 10, TimeUnit.SECONDS);
        return "success.";
    }

    @GetMapping("/get")
    public String get() {
        Set<String> keys = redisTemplate.keys("*");
        if (keys == null || keys.size() == 0) {
            return null;
        }
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        StringBuilder sb = new StringBuilder();
        for (String key : keys) {
            Object val = ops.get(key);
            sb.append(key)
                    .append("=")
                    .append(val)
                    .append(", ");
        }
        return sb.toString();
    }

    @GetMapping("/del")
    public String del() {
        Set<String> keys = redisTemplate.keys("*");
        if (keys == null || keys.size() == 0) {
            return null;
        }
        for (String key : keys) {
            Boolean ans = redisTemplate.delete(key);
            System.out.println(key + "删除是否成功: " + ans);
        }
        return "success.";
    }

}
